package cn.lyq.card.ui.wallet

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.BillInfo
import cn.lyq.card.data.model.BillTypeInfo
import cn.lyq.card.data.model.PageInfo
import cn.lyq.card.data.model.WalletInfo
import cn.lyq.card.data.src.Result
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.BusTag
import cn.lyq.card.manager.UserManager
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_wallet.*
import kotlinx.android.synthetic.main.layout_expend_type.*


class WalletActivity : BaseActivity() {

    private var billType = 0
    private val page = PageInfo()
    private var mInfo: WalletInfo? = null
    private val mAdapter by lazy {
        WalletAdapter()
    }
    private val mTypeAdapter by lazy {
        BillTypeAdapter()
    }
    private val mModel by lazy {
        getVM(WalletVM::class.java)
    }

    override fun getLayoutId(): Int {
        return R.layout.act_wallet
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_my_wallet)
        groupExpendType.visibility = View.GONE

        rvExpendType.layoutManager = GridLayoutManager(this, 3)
        rvExpendType.adapter = mTypeAdapter

        rv.layoutManager = LinearLayoutManager(this)
        rv.adapter = mAdapter
        mAdapter.setEmptyView(R.layout.layout_empty)
        mAdapter.loadMoreModule.apply {
            checkDisableLoadMoreIfNotFullPage()
            preLoadNumber = 2
            setOnLoadMoreListener {
                getData(false)
            }
        }
    }

    override fun isLightBarColor(): Boolean {
        return true
    }

    override fun initListener() {
        super.initListener()
        tvCashQuickly.setClick {
            if (UserManager.bankCardInfo == null) {
                setBarColor(true)
                BankCardAddFg().show(this)
            } else {
                CashMsgActivity.start(this, mInfo)
            }
        }
        tvTypeClick.setClick {
            if (mTypeAdapter.data.size == 0) {
                showLoading()
                getBillType()
            } else {
                groupExpendType.visibility = View.VISIBLE
            }
        }
        groupExpendType.setClick {
            groupExpendType.visibility = View.GONE
        }
        refreshLayout.setOnRefreshListener {
            getData(true)
        }
        mTypeAdapter.setOnItemClickListener { _, _, position ->
            mTypeAdapter.data[position].run {
                billType = typeId
                tvType.text = typeName
            }
            getData(true)
            groupExpendType.visibility = View.GONE
        }
    }

    override fun initObserver() {
        super.initObserver()
        setTypeData()
        if (UserManager.bankCardInfo == null) {
            getBankCardInfo()
        }
        getData(true)

        getWalletInfo()
    }

    private fun getWalletInfo() {
        mModel.getWalletInfo().observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.getMsg())
                    dismissLoading()
                }
                Status.SUCCESS -> {
                    it.data?.run {
                        mInfo = this
                        tvBalance.text = balance ?: "0.00"
                        tvReturnMoney.text = cashBackBalance ?: "0.00"
                        tvSubsidyMoney.text = subsidyBalance ?: "0.00"
                        tvShareMoney.text = personalBalance ?: "0.00"
                    }
                    dismissLoading()
                }
            }
        })
    }

    private fun getBankCardInfo() {
        mModel.getBankCardInfo().observe(this, Observer {
            if (it.status == Status.SUCCESS) {
                UserManager.bankCardInfo = it.requireData()
            }
        })
    }

    private fun setTypeData() {
        if (UserManager.billTypeList.isEmpty()) {
            getBillType()
        } else {
            val data = mutableListOf<BillTypeInfo>()
            UserManager.billTypeList.map {
                data.add(it.value)
            }
            mTypeAdapter.setList(data)
        }
    }

    private fun getData(isRefresh: Boolean) {
        val target = page.update(isRefresh)
        mModel.getBillList(billType, target).observe(this, Observer {
            when (it?.status) {
                Status.SUCCESS -> loadSuccess(it)
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.getMsg())
                    refreshLayout.isRefreshing = false
                    page.fail()
                    mAdapter.loadMoreModule.loadMoreFail()
                }
                Status.LOADING -> {
                    if (page.isRefresh() && !refreshLayout.isRefreshing) {
                        refreshLayout.isRefreshing = true
                    }
                }
            }
        })
    }

    private fun getBillType() {
        mModel.getTypeList().observe(this, Observer {
            when (it?.status) {
                Status.SUCCESS -> getBillTypeSuccess(it)
                Status.ERROR -> {
                    dismissLoading()
                    ToastUtils.showShort(it.message.getMsg())
                }
                else -> {
                }
            }
        })
    }

    private fun getBillTypeSuccess(it: Result<MutableList<BillTypeInfo>>) {
        val map = UserManager.billTypeList
        it.requireData().forEach { type ->
            map[type.typeId] = type
        }
        mAdapter.notifyDataSetChanged()
        mTypeAdapter.setList(it.requireData())
        dismissLoading()
    }


    private fun loadSuccess(it: Result<MutableList<BillInfo>>) {
        val temp = it.requireData()
        if (page.isRefresh()) {
            mAdapter.setList(temp)
            rv.scrollToPosition(0)
        } else {
            mAdapter.addData(temp)
        }
        page.success()
        if (temp.size < mModel.pageSize) {
            mAdapter.loadMoreModule.loadMoreEnd()
        } else {
            mAdapter.loadMoreModule.loadMoreComplete()
        }
        refreshLayout.isRefreshing = false
    }

    @BusUtils.Bus(tag = BusTag.REFRESH_BALANCE, threadMode = BusUtils.ThreadMode.MAIN)
    fun refreshBalance() {
        getWalletInfo()
    }
}